<template>
    <div>
        <van-tabs :before-change="beforeChange" sticky animated swipeable>
            <van-tab v-for="(item,index) in indexSpan" :title="item.title" :badge="item.badge" :key="index">
                <div style="text-align: left;margin: 10px 10px " >
                    <van-collapse v-model="activeName" accordion @change="vanCollapseChang">
                        <van-collapse-item v-for="(itemOrder,index) in orderListGorup" :key="index" :title=itemOrder.ress :name=index>
                            <template #title>
                                <div>
                                    <span>{{itemOrder.ress}}</span>
                                    <span style="float: right"><van-tag round size="medium" color="#CCE8CF">{{itemOrder.countNum}}</van-tag> </span>
                                </div>
                            </template>
                            <van-cell  :name="index" v-for="(orderItem,key) in orderList" :key="key" @click="collapseChange(orderItem)" >
                                <template #title>
                                    <div>
                                        <span>{{orderItem.address}}</span>
                                        <span style="float: right">

                                            <van-tag v-if="orderItem.status === 0" round size="medium" type="warning">{{orderItem.createTime}}</van-tag>
                                            <van-tag v-if="orderItem.status === 1" round size="medium" type="primary">{{orderItem.createTime}}</van-tag>
                                            <van-tag v-if="orderItem.status === 2" round size="medium" color="#7232dd">{{orderItem.createTime}}</van-tag>
                                            <van-tag v-if="orderItem.status === 3" round size="medium" type="success">{{orderItem.createTime}}</van-tag>
                                            <van-tag v-if="orderItem.status === 4" round size="medium" type="danger">{{orderItem.createTime}}</van-tag>

                                        </span>
                                    </div>
                                </template>
                            </van-cell>
                        </van-collapse-item>
                    </van-collapse>
                </div>
            </van-tab>
        </van-tabs>
        <van-popup v-model="showOrderDesc"  position="bottom" :style="{ height: '80%' }">
            <div style="margin-bottom: 40px;text-align: left">
                <div v-for="(desc,key) in orderDescList" :key="key" style="margin-top: 5px;" >
                    <van-card
                            :price="(desc.price/100)"
                            :desc="desc.desc"
                            :title="desc.title"
                            :origin-price="desc.originPrice/100"
                            :thumb="desc.imgUrl"
                            :num="desc.num"
                    >
                        <template #tags>
                            <van-tag plain type="danger" v-for="(tag,id) in desc.vanTag.split(';')" :key="id">{{tag}}</van-tag>
                        </template>
                    </van-card>
                </div>
            </div>
            <div>
                <van-submit-bar v-if="orderIndex == 0"  :price="totalOrderPrice" button-text="接单" @submit="onSubmit(editOrder)" >
                    <van-goods-action-icon icon="delete-o" text="订单异常关闭"  @click="onSubmitClose(editOrder)" />
                </van-submit-bar>
                <van-submit-bar v-if="orderIndex == 1" :price="totalOrderPrice" button-text="开始配送" @submit="onSubmit(editOrder)" >
                    <van-goods-action-icon icon="delete-o" text="订单异常关闭" @click="onSubmitClose(editOrder)" />
                </van-submit-bar>
                <van-submit-bar v-if="orderIndex == 2" :price="totalOrderPrice" button-text="已完成" @submit="onSubmit(editOrder)" />
            </div>
        </van-popup>
    </div>
</template>

<script>
    import { Toast } from 'vant';
    import { Notify } from 'vant';
    import { Dialog } from 'vant';
    import { useTitle } from '@vueuse/core';
    export default {
        name: "ShopAdmin",
        data() {
            return {
                activeName: '',
                indexSpan:[
                    {
                        title:"已下单",
                        badge:""
                    },
                    {
                        title:"已接单",
                        badge:""
                    },
                    {
                        title:"配送中",
                        badge:""
                    },
                    {
                        title:"已完成",
                        badge:""
                    },
                    {
                        title:"异常关闭",
                        badge:""
                    }],
                orderDescList:[],
                orderListGorup:[],
                orderList:[],
                region:"",
                showOrderDesc:false,
                totalOrderPrice:0,
                editOrder:{},
                orderIndex:0,
                timerId:null
            }
        },
        methods: {
            vanCollapseChang(index){
                var orderGroup = this.orderListGorup[index]
                if(orderGroup !== undefined){
                    this.$axios.getOrderIds({"ids":orderGroup.ids}).then(res => {
                        this.orderList = res.data.data
                    })
                }
            },
            onSubmit(item){
                const toast = Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                });
                this.$axios.updateOrderStatus(item).then(res => {
                    console.log(res)
                    if(this.orderList.length == 1){
                        this.activeName = ""
                        this.$axios.orderGroupList({"communityCode":this.region,"status":this.orderIndex}).then(res => {
                            this.orderListGorup = res.data.data
                            toast.clear();
                            this.showOrderDesc = false;
                        })
                    } else {
                        this.$axios.orderGroupList({"communityCode":this.region,"status":this.orderIndex}).then(res => {
                            this.orderListGorup = res.data.data
                            var orderGroup = this.orderListGorup[this.activeName]
                            this.$axios.getOrderIds({"ids":orderGroup.ids}).then(res => {
                                this.orderList = res.data.data
                                toast.clear();
                                this.showOrderDesc = false;
                            })
                        })
                    }
                    this.$axios.tabNum({"communityCode":this.region}).then(tab => {
                        let tags = tab.data.data
                        this.indexSpan.forEach(span => {
                            span.badge = ""
                        })
                        tags.forEach(item => {
                            this.indexSpan[item.status].badge = item.num
                        })
                    })

                })
            },
            onSubmitClose(item){
                Dialog.confirm({
                    title: '异常订单删除',
                    message: '请确认是否将该订单标记为异常订单【'+item.orderCode+'】',
                })
                .then(() => {
                    const toast = Toast.loading({
                        message: '加载中...',
                        forbidClick: true,
                        loadingType: 'spinner',
                        duration: 0
                    });
                    item.status = 4
                    this.$axios.updateOrderStatus(item).then(res => {
                        console.log(res)
                        if(this.orderList.length == 1){
                            this.activeName = ""
                            this.$axios.orderGroupList({"communityCode":this.region,"status":this.orderIndex}).then(res => {
                                this.orderListGorup = res.data.data
                                toast.clear();
                                this.showOrderDesc = false;
                            })
                        } else {
                            this.$axios.orderGroupList({"communityCode":this.region,"status":this.orderIndex}).then(res => {
                                this.orderListGorup = res.data.data
                                var orderGroup = this.orderListGorup[this.activeName]
                                this.$axios.getOrderIds({"ids":orderGroup.ids}).then(res => {
                                    this.orderList = res.data.data
                                    toast.clear();
                                    this.showOrderDesc = false;
                                })
                            })
                        }
                        this.$axios.tabNum({"communityCode":this.region}).then(tab => {
                            let tags = tab.data.data
                            this.indexSpan.forEach(span => {
                                span.badge = ""
                            })
                            tags.forEach(item => {
                                this.indexSpan[item.status].badge = item.num
                            })
                        })

                    })
                })
                .catch(() => {
                    // on cancel
                });
            },
            beforeChange(index) {
                this.activeName = ""
                this.orderIndex = index
                this.orderDescList = []
                this.orderListGorup = []
                return new Promise((resolve) => {
                    if(this.region.trim() == null || this.region.trim() == undefined || this.region.trim() == ""){
                        Notify({ type: 'warning', message: "抱歉，没有获取到区域信息。请扫描二维码查看" });
                    } else {
                        const toast = Toast.loading({
                            message: '加载中...',
                            forbidClick: true,
                            loadingType: 'spinner',
                            duration: 0
                        });
                        this.$axios.tabNum({"communityCode":this.region}).then(tab => {
                            let tags = tab.data.data
                            this.indexSpan.forEach(span => {
                                span.badge = ""
                            })
                            tags.forEach(item => {
                                this.indexSpan[item.status].badge = item.num
                            })

                        })
                        this.$axios.orderGroupList({"communityCode":this.region,"status":this.orderIndex}).then(res => {
                            this.orderListGorup = res.data.data
                            toast.clear();
                            resolve(true);
                        })

                    }
                });
            },
            collapseChange(item) {
                this.totalOrderPrice = item.totalAmount;
                this.editOrder = item;
                this.showOrderDesc = true;
                const toast = Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                });
                this.$axios.orderDescList({orderCode:item.orderCode}).then(res => {
                    this.orderDescList = res.data.data
                    toast.clear();
                })
            },
            updateMessage() {
                this.$axios.tabNum({"communityCode":this.region}).then(tab => {
                    let tags = tab.data.data
                    let itemNum = 0;
                    tags.forEach(item => {
                        if(item.status == 0){
                            itemNum = item.num
                        }
                    })
                    if(itemNum > this.indexSpan[0].badge ){
                        const audio = new Audio('http://zhnc.cokcc.top/order.mp3');
                        audio.play();
                        this.indexSpan.forEach(span => {
                            span.badge = ""
                        })
                        tags.forEach(item => {
                            this.indexSpan[item.status].badge = item.num
                        })
                        if(this.orderIndex == 0){
                            this.$axios.orderGroupList({"communityCode":this.region,"status":0}).then(res => {
                                if(this.orderListGorup.length < res.data.data.length){
                                    this.activeName = ""
                                }
                                this.orderListGorup = res.data.data
                                if(this.activeName !== ""){
                                    var orderGroup = this.orderListGorup[this.activeName]
                                    this.$axios.getOrderIds({"ids":orderGroup.ids}).then(res => {
                                        this.orderList = res.data.data
                                    })
                                }
                            })
                        }
                    }
                })
            }
        },
        beforeDestroy() {
            // 清除定时器
            if (this.timerId) {
                clearInterval(this.timerId);
            }
        },
        mounted() {
            // 创建定时器，每2秒执行一次updateMessage方法
            this.timerId = setInterval(this.updateMessage, 30000);
        },
        created(){
            let href = window.location.href;
            let region= href.substring(href.indexOf("=") + 1 , href.length);
            this.region = region;
            if(region.trim() == null || region.trim() == undefined || region.trim() == ""){
                Notify({ type: 'warning', message: "抱歉，没有获取到区域信息。请扫描二维码查看" });
            } else {
                const toast = Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                });
                this.$axios.orderGroupList({"communityCode":region,"status":0}).then(res => {
                    this.orderListGorup = res.data.data
                    this.$axios.tabNum({"communityCode":this.region}).then(tab => {
                        let tags = tab.data.data
                        this.indexSpan.forEach(span => {
                            span.badge = ""
                        })
                        tags.forEach(item => {
                            this.indexSpan[item.status].badge = item.num
                        })
                    })

                    toast.clear();
                })
            }
            this.$axios.getRegion({"codeType":region}).then(res => {
                let index = Object.keys(res.data.data.address)
                var indexItem = ""
                index.forEach(item => {
                    indexItem = indexItem + "-" + item
                })
                useTitle(indexItem.slice(1))
            }).catch(error => {
                console.log(error)
            })
        }
    }
</script>

<style scoped>

</style>